package com.hy.mydesktop.client.component.factory;

import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import com.extjs.gxt.ui.client.data.BaseModel;
import com.extjs.gxt.ui.client.data.BaseModelData;
import com.extjs.gxt.ui.client.data.ModelData;
import com.extjs.gxt.ui.client.event.BaseEvent;
import com.extjs.gxt.ui.client.event.ComponentEvent;
import com.extjs.gxt.ui.client.event.Events;
import com.extjs.gxt.ui.client.event.FieldEvent;
import com.extjs.gxt.ui.client.event.Listener;
import com.extjs.gxt.ui.client.event.SelectionListener;
import com.extjs.gxt.ui.client.mvc.Dispatcher;
import com.extjs.gxt.ui.client.widget.form.TextField;
import com.extjs.gxt.ui.client.widget.grid.CellEditor;
import com.extjs.gxt.ui.client.widget.grid.ColumnConfig;
import com.extjs.gxt.ui.client.widget.grid.ColumnModel;
import com.google.gwt.core.client.GWT;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.hy.mydesktop.client.component.event.AppEvents;
import com.hy.mydesktop.client.component.meta.AbstractComponetModelEnum;
import com.hy.mydesktop.client.component.meta.ShortcutModelEnum;
import com.hy.mydesktop.client.component.meta.TextFieldModelEnum;
import com.hy.mydesktop.client.component.mvc.event.EventStructureMetaModel;
import com.hy.mydesktop.client.component.type.ComponentControllerEnum;
import com.hy.mydesktop.client.rpc.ServiceInvoker;
import com.hy.mydesktop.client.rpc.ServiceInvokerAsync;
import com.hy.mydesktop.shared.persistence.domain.gxt.GxtComponentMetaNodeModel;
import com.hy.mydesktop.shared.rpc.meta.GxtToSeamServiceParameter;
import com.hy.mydesktop.shared.rpc.meta.GxtToSeamServiceResult;
import com.hy.mydesktop.shared.rpc.util.ComponentControllerEnumConverter;

/**
 * 
 * <ul>
 * <li>开发作者：汤莉</li>
 * <li>设计日期：2010-8-29；时间：下午05:07:01</li>
 * <li>类型名称：TextFieldFactory</li>
 * <li>设计目的：</li>
 * </ul>
 * <ul>
 * <b>修订编号：</b>
 * <li>修订日期：</li>
 * <li>修订作者：</li>
 * <li>修订原因：</li>
 * <li>修订内容：</li>
 * </ul>
 */
public class TextFieldFactory {

	/**
	 * 
	 * <ul>
	 * <li>方法含义：创建文本框</li>
	 * <li>方法作者：汤莉</li>
	 * <li>编写日期：2010-8-29；时间：下午下午05:08:20</li>
	 * </ul>
	 * <ul>
	 * <b>修订编号：</b>
	 * <li>修订日期：</li>
	 * <li>修订作者：</li>
	 * <li>修订原因：</li>
	 * <li>修订内容：</li>
	 * </ul>
	 * @param gxtComponentMetaModel
	 * @return
	 */
	public static TextField<String> createTextField(GxtComponentMetaNodeModel gxtComponentMetaModel){
		return configureTextField(gxtComponentMetaModel);
		
	}
	
	/**
	 * 
	 * <ul>
	 * <li>方法含义：配置文本框的属性</li>
	 * <li>方法作者：汤莉</li>
	 * <li>编写日期：2010-8-29；时间：下午下午05:09:06</li>
	 * </ul>
	 * <ul>
	 * <b>修订编号：</b>
	 * <li>修订日期：</li>
	 * <li>修订作者：</li>
	 * <li>修订原因：</li>
	 * <li>修订内容：</li>
	 * </ul>
	 * @param gxtComponentMetaNodeModel
	 * @return
	 */
	private static TextField<String> configureTextField(GxtComponentMetaNodeModel gxtComponentMetaNodeModel){
		
		final TextField<String> textField=createDefalutTextField();
//		text = AbstractComponetFactory.configureAbstractComponet(text, gxtComponentMetaNodeModel);
		 AbstractComponetFactory.configureAbstractComponet(textField, gxtComponentMetaNodeModel);
		// AbstractComponetFactory.configureGxtToSeamServiceParameterModel(text, gxtComponentMetaNodeModel);

		//数据加载
			if(gxtComponentMetaNodeModel.get(AbstractComponetModelEnum.GXTTOSEAMSERVICEPARAMETERMODEL.name().toLowerCase())!=null){
				final ServiceInvokerAsync serviceInvoker = GWT.create(ServiceInvoker.class);
				final GxtToSeamServiceParameter gxtToSeamServiceParameter = textField.getData("gxtToSeamServiceParameter");
				/*final GxtToSeamServiceParameter gxtToSeamServiceParameter = new GxtToSeamServiceParameter();
				gxtToSeamServiceParameter.setServiceComponentName("com.test.server.business.PersonService");
				gxtToSeamServiceParameter.setServiceMethodName("loadTextFieldData");
				ModelData[] methodArguments2 = new BaseModelData[1];
				methodArguments2[0] = new BaseModel();
				gxtToSeamServiceParameter.setMethodArguments(methodArguments2 );*/
				
				serviceInvoker.callService(gxtToSeamServiceParameter,
						new AsyncCallback<GxtToSeamServiceResult>() {

							@Override
							public void onSuccess(GxtToSeamServiceResult result) {
								List<String> bmBaseModels = new LinkedList<String>();
								ModelData modelData = result.getResult();
								String text = null;
								if (modelData.get("string")!=null) {
									text = modelData.get("string");
								}else if (modelData.get(textField.getId())!=null) {
									text = modelData.get(textField.getId());
								}else if (modelData.get(textField.getId())!=null) {
									text = modelData.get(textField.getId());
								}else {
									text = modelData.get(textField.getName());

								}
								bmBaseModels.get(0);
								textField.setValue(text);
								/*List<GxtComponentMetaNodeModel> bmBaseModels = new LinkedList<GxtComponentMetaNodeModel>();
								ModelData modelData = result.getResult();
								bmBaseModels = modelData.get("listOfModelData");
								for (GxtComponentMetaNodeModel gxtComponentMetaNodeModel : bmBaseModels) {
									gxtComponentMetaNodeModel.setComponentControllerEnum(
											ComponentControllerEnumConverter.getComponentControllerEnum(gxtComponentMetaNodeModel.getComponentControllerEnumIndex()));
									//System.err.println("$$$$$$$$$" + gxtComponentMetaNodeModel.getComponentControllerEnum());
								}*/
															
							}

							@Override
							public void onFailure(Throwable caught) {
								System.err.println("#### Rpc Exception is beginning ####");
								System.err.println(caught);
								System.err.println("#### Rpc Exception is over #### ");
								caught.printStackTrace();
							}
						});
				
			}
		//数据加载 废弃
		if(false && gxtComponentMetaNodeModel.get(TextFieldModelEnum.DATALOAD.name().toLowerCase())==null){
			final ServiceInvokerAsync serviceInvoker = GWT.create(ServiceInvoker.class);
			final GxtToSeamServiceParameter gxtToSeamServiceParameter = new GxtToSeamServiceParameter();
			gxtToSeamServiceParameter.setServiceComponentName("com.test.server.business.PersonService");
			gxtToSeamServiceParameter.setServiceMethodName("loadTextFieldData");
//			gxtToSeamServiceParameter.setServiceMethodName("getList2");
//			gxtToSeamServiceParameter.setServiceMethodName("getEnums");
			BaseModel[] methodArguments2 = new BaseModel[1];
			methodArguments2[0] = new BaseModel();
			gxtToSeamServiceParameter.setMethodArguments(methodArguments2 );
			
			serviceInvoker.callService(gxtToSeamServiceParameter,
					new AsyncCallback<GxtToSeamServiceResult>() {

						@Override
						public void onSuccess(GxtToSeamServiceResult result) {
							List<String> bmBaseModels = new LinkedList<String>();
							ModelData modelData = result.getResult();
							bmBaseModels = modelData.get("listOfModelData");
							bmBaseModels.get(0);
							textField.setValue(bmBaseModels.get(0));
							/*List<GxtComponentMetaNodeModel> bmBaseModels = new LinkedList<GxtComponentMetaNodeModel>();
							ModelData modelData = result.getResult();
							bmBaseModels = modelData.get("listOfModelData");
							for (GxtComponentMetaNodeModel gxtComponentMetaNodeModel : bmBaseModels) {
								gxtComponentMetaNodeModel.setComponentControllerEnum(
										ComponentControllerEnumConverter.getComponentControllerEnum(gxtComponentMetaNodeModel.getComponentControllerEnumIndex()));
								//System.err.println("$$$$$$$$$" + gxtComponentMetaNodeModel.getComponentControllerEnum());
							}*/
														
						}

						@Override
						public void onFailure(Throwable caught) {
							System.out.println("#### Rpc Exception is ####"+caught +"When get the List<GxtComponentMetaNodeModel>");
							caught.printStackTrace();
						}
					});
			
		}
		if(gxtComponentMetaNodeModel.get(TextFieldModelEnum.ALLOWBLANK.name().toLowerCase())!=null){
			//是否允许为空
			textField.setAllowBlank((Boolean)gxtComponentMetaNodeModel.get(TextFieldModelEnum.ALLOWBLANK.name().toLowerCase()));
		}
		if(gxtComponentMetaNodeModel.get(TextFieldModelEnum.EMPTYTEXT.name().toLowerCase())!=null){
			//空值文本
			textField.setEmptyText((String)gxtComponentMetaNodeModel.get(TextFieldModelEnum.EMPTYTEXT.name().toLowerCase()));
		}
		if(gxtComponentMetaNodeModel.get(TextFieldModelEnum.MAXLENGTH.name().toLowerCase())!=null){
			//设置文本框输入的长度
			textField.setMaxLength((Integer)gxtComponentMetaNodeModel.get(TextFieldModelEnum.MAXLENGTH.name().toLowerCase()));
		}
		if(gxtComponentMetaNodeModel.get(TextFieldModelEnum.MINLENGTH.name().toLowerCase())!=null){
			//设置文本框输入值的最小长度
			textField.setMinLength((Integer)gxtComponentMetaNodeModel.get(TextFieldModelEnum.MINLENGTH.name().toLowerCase()));
		}
		if(gxtComponentMetaNodeModel.get(TextFieldModelEnum.PASSWORD.name().toLowerCase())!=null){
			//设置密码框样式
			textField.setPassword((Boolean)gxtComponentMetaNodeModel.get(TextFieldModelEnum.PASSWORD.name().toLowerCase()));
		}
		if(gxtComponentMetaNodeModel.get(TextFieldModelEnum.REGEX.name().toLowerCase())!=null){
			//设置正则表达式
			textField.setRegex((String)gxtComponentMetaNodeModel.get(TextFieldModelEnum.REGEX.name().toLowerCase()));
		}
		if(gxtComponentMetaNodeModel.get(TextFieldModelEnum.VALUE.name().toLowerCase())!=null){
			//设置值
			textField.setValue((String)gxtComponentMetaNodeModel.get(TextFieldModelEnum.VALUE.name().toLowerCase()));
		}
		if(gxtComponentMetaNodeModel.get(TextFieldModelEnum.FIELDLABEL.name().toLowerCase())!=null){
			//设置标签
			textField.setFieldLabel((String)gxtComponentMetaNodeModel.get(TextFieldModelEnum.FIELDLABEL.name().toLowerCase()));
		}
		if(gxtComponentMetaNodeModel.get(TextFieldModelEnum.NAME.name().toLowerCase())!=null){
			//设置控件名
			textField.setName((String)gxtComponentMetaNodeModel.get(TextFieldModelEnum.NAME.name().toLowerCase()));
		}
		if(gxtComponentMetaNodeModel.get(ShortcutModelEnum.REGISTEREVENTTYPES.name().toLowerCase())!=null){
			
			final Map<String,Object> appEventCodes = gxtComponentMetaNodeModel.get(ShortcutModelEnum.REGISTEREVENTTYPES.name().toLowerCase());
			for ( final String code : appEventCodes.keySet()) {
				Integer i = Integer.valueOf(code);
				switch (i) {
		            case 1://Integer.valueOf("0001")
		            	//shortcutController.addRegisterEventType(AppEvents.Login);
		            	
		                break;
		            case 2://Integer.valueOf("0002")
		            	//shortcutController.addRegisterEventType(AppEvents.DESKTOP_INIT_FOR_LOGGED_IN_USER);	
		                break;
		            case 301://Integer.valueOf("0301")
		            	
		            	
					    /**
						 * 窗口中TextField文本域的监听器
						 */
					  
					    textField.addListener(Events.OnClick, new Listener<FieldEvent>() {

							@Override
							public void handleEvent(FieldEvent be) {
								//itemSelected(desktop,ce);
						    	  //
						    	  Map<String, Object> data = (Map<String, Object>)appEventCodes.get(code);
						    	  EventStructureMetaModel eventstructuremetamodel = 
										 (EventStructureMetaModel)data.get("eventstructuremetamodel");
						    	  System.out.println("text触发AppEvents.FORM_TEXTFIELD_ONCLICK事件:"
						    			  +eventstructuremetamodel.getControllerId()
						    			  +eventstructuremetamodel.getResponseModeId());
						    	 //Dispatcher.forwardEvent(AppEvents.FORM_TEXTFIELD_ONCLICK,data);
						    	 textField.setValue("reponse..........");
						    	 System.err.println(" text.setValue(reponse..........)............");
							}
						});
					   
//						Dispatcher.forwardEvent(AppEvents.DESKTOP_SHORTCUT_ONCLICK_INIT, data);
						//TODO 在抛出事件时，如何传输APPEVENT需要的data ？？
		                break;
		           
		            case 101://Integer.valueOf("0101")
		            	//shortcutController.addRegisterEventType(AppEvents.WINDOW_ININT);
		                break;
	           		           
		            default:
		                break;
		        }
			}
		
		}
		//Listener<FieldEvent> textFieldListener = new Listener<FieldEvent>();
	   /* text.addListener(Events.OnClick, new Listener<BaseEvent>() {

			@Override
			public void handleEvent(BaseEvent be) {
				 System.err.println(" text.setValue(reponse..........)............");
			}
		});*/
	   // System.err.println(" text.setValue(reponse..........)............");
		return textField;
	}
	
	/**
	 * 
	 * <ul>
	 * <li>方法含义：创建默认的文本框</li>
	 * <li>方法作者：汤莉</li>
	 * <li>编写日期：2010-8-29；时间：下午下午05:10:06</li>
	 * </ul>
	 * <ul>
	 * <b>修订编号：</b>
	 * <li>修订日期：</li>
	 * <li>修订作者：</li>
	 * <li>修订原因：</li>
	 * <li>修订内容：</li>
	 * </ul>
	 * @return
	 */
	private static TextField<String> createDefalutTextField(){
		TextField<String> text=new TextField<String>();
		text.setFieldLabel("FieldLabel");
		text.setAllowBlank(true);
		return text;
	}
}
